package com.weijian.controller;

import com.weijian.common.Result;
import com.weijian.entity.VideoInfo;
import com.weijian.entity.VideoPlaybackProgress;
import com.weijian.service.MinIOService;
import com.weijian.service.VideoInfoService;
import com.weijian.service.VideoPlaybackProgressService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 视频管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/videos")
@RequiredArgsConstructor
@Tag(name = "视频管理", description = "提供视频信息查询和管理相关接口")
public class VideoController {

    private final VideoInfoService videoInfoService;
    private final MinIOService minIOService;
    private final VideoPlaybackProgressService playbackProgressService;

    /**
     * 获取视频列表（分页）
     */
    @GetMapping
    @Operation(summary = "获取视频列表", description = "分页获取视频列表")
    public Result<?> getVideoList(
            @Parameter(description = "页码", example = "1")
            @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量", example = "10")
            @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            log.info("获取视频列表，页码: {}, 每页数量: {}", pageNum, pageSize);
            return Result.success(videoInfoService.getVideoPage(pageNum, pageSize));
        } catch (Exception e) {
            log.error("获取视频列表失败: {}", e.getMessage(), e);
            return Result.error("获取视频列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取视频详情
     */
    @GetMapping("/{id}")
    @Operation(summary = "获取视频详情", description = "根据ID获取视频详细信息")
    public Result<?> getVideoDetail(
            @Parameter(description = "视频ID", example = "1", required = true)
            @PathVariable Long id) {
        try {
            log.info("获取视频详情，ID: {}", id);
            VideoInfo videoInfo = videoInfoService.getById(id);
            if (videoInfo == null) {
                return Result.error(404, "视频不存在");
            }
            return Result.success(videoInfo);
        } catch (Exception e) {
            log.error("获取视频详情失败: {}", e.getMessage(), e);
            return Result.error("获取视频详情失败: " + e.getMessage());
        }
    }

    /**
     * 删除视频
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除视频", description = "根据ID删除视频文件和记录")
    public Result<?> deleteVideo(
            @Parameter(description = "视频ID", example = "1", required = true)
            @PathVariable Long id) {
        try {
            log.info("删除视频，ID: {}", id);
            boolean result = videoInfoService.deleteVideo(id);
            if (result) {
                return Result.success("视频删除成功");
            } else {
                return Result.error("视频删除失败");
            }
        } catch (Exception e) {
            log.error("删除视频失败: {}", e.getMessage(), e);
            return Result.error("删除视频失败: " + e.getMessage());
        }
    }

    /**
     * 获取视频播放URL
     */
    @GetMapping("/{id}/play-url")
    @Operation(summary = "获取视频播放URL", description = "获取视频的预签名播放URL")
    public Result<?> getVideoPlayUrl(
            @Parameter(description = "视频ID", example = "1", required = true)
            @PathVariable Long id) {
        try {
            log.info("获取视频播放URL，ID: {}", id);
            VideoInfo videoInfo = videoInfoService.getById(id);
            if (videoInfo == null) {
                return Result.error(404, "视频不存在");
            }

            // 获取预签名URL
            String playUrl = minIOService.getPresignedUrl(videoInfo.getFilePath());

            return Result.success(playUrl);
        } catch (Exception e) {
            log.error("获取视频播放URL失败: {}", e.getMessage(), e);
            return Result.error("获取视频播放URL失败: " + e.getMessage());
        }
    }

    /**
     * 保存视频播放进度
     */
    @PostMapping("/{id}/progress")
    @Operation(summary = "保存视频播放进度", description = "保存用户观看视频的进度")
    public Result<?> savePlaybackProgress(
            @Parameter(description = "视频ID", example = "1", required = true)
            @PathVariable Long id,
            @Parameter(description = "用户ID", example = "1001", required = true)
            @RequestParam Long userId,
            @Parameter(description = "播放进度（秒）", example = "120", required = true)
            @RequestParam Integer progress,
            @Parameter(description = "视频总时长（秒）", example = "300")
            @RequestParam(required = false, defaultValue = "0") Integer duration) {
        try {
            log.info("保存视频播放进度，视频ID: {}, 用户ID: {}, 进度: {}秒", id, userId, progress);

            // 验证视频是否存在
            VideoInfo videoInfo = videoInfoService.getById(id);
            if (videoInfo == null) {
                return Result.error(404, "视频不存在");
            }

            // 保存播放进度
            boolean success = playbackProgressService.saveOrUpdateProgress(
                    userId, id, progress, duration > 0 ? duration : videoInfo.getDuration());

            if (success) {
                return Result.success("播放进度保存成功");
            } else {
                return Result.error("播放进度保存失败");
            }
        } catch (Exception e) {
            log.error("保存视频播放进度失败: {}", e.getMessage(), e);
            return Result.error("保存视频播放进度失败: " + e.getMessage());
        }
    }

    /**
     * 获取视频播放进度
     */
    @GetMapping("/{id}/progress")
    @Operation(summary = "获取视频播放进度", description = "获取用户观看视频的进度")
    public Result<?> getPlaybackProgress(
            @Parameter(description = "视频ID", example = "1", required = true)
            @PathVariable Long id,
            @Parameter(description = "用户ID", example = "1001", required = true)
            @RequestParam Long userId) {
        try {
            log.info("获取视频播放进度，视频ID: {}, 用户ID: {}", id, userId);

            // 验证视频是否存在
            VideoInfo videoInfo = videoInfoService.getById(id);
            if (videoInfo == null) {
                return Result.error(404, "视频不存在");
            }

            // 获取播放进度
            VideoPlaybackProgress progress = playbackProgressService.getProgressByUserAndVideo(userId, id);

            if (progress == null) {
                return Result.success("暂无播放记录", null);
            }

            return Result.success(progress);
        } catch (Exception e) {
            log.error("获取视频播放进度失败: {}", e.getMessage(), e);
            return Result.error("获取视频播放进度失败: " + e.getMessage());
        }
    }
}